package com.open.capacity.utils;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataAccessException;
import org.springframework.data.redis.connection.RedisConnection;
import org.springframework.data.redis.core.RedisCallback;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.util.Set;
import java.util.concurrent.TimeUnit;

/**
 * @author ftquan
 * @since 2019/1/29
 */
@Component
public class JedisUtil {

    private static RedisTemplate redisTemplate;


    @Autowired
    public void setRedisTemplate(RedisTemplate redisTemplate) {
        JedisUtil.redisTemplate = redisTemplate;
    }

    /**
     * 获取redis键值-object
     */
    public static Object getObject(String key) {
        return redisTemplate.opsForValue().get(key);
    }

    /**
     * 设置redis键值-object
     *
     * @param key
     * @param value
     */
    public static void setObject(String key, Object value) {
        redisTemplate.opsForValue().set(key, value);
    }

    /**
     * 设置redis键值-object-expiretime
     */
    public static void setObject(String key, Object value, int expiretime) {
        redisTemplate.opsForValue().set(key, value, expiretime, TimeUnit.MILLISECONDS);
    }


    /**
     * 删除key
     *
     * @param key
     */
    public static Boolean delKey(String key) {
        return redisTemplate.opsForValue().getOperations().delete(key);
    }

    /**
     * key是否存在
     *
     * @param key
     * @return java.lang.Boolean
     */
    public static Boolean exists(String key) {
        return redisTemplate.opsForValue().getOperations().hasKey(key);
    }


    public static Object flushDB() {
        return redisTemplate.execute(new RedisCallback<String>() {
            @Override
            public String doInRedis(RedisConnection redisConnection) throws DataAccessException {
                redisConnection.flushDb();
                return "ok";
            }
        });
    }

    public static long dbSize() {
        return (long) redisTemplate.execute(new RedisCallback<Long>() {
            @Override
            public Long doInRedis(RedisConnection connection) throws DataAccessException {
                return connection.dbSize();
            }
        });
    }


    public static Set<String> keys() {
        return redisTemplate.keys("*");
    }

    public static Boolean setnx(String key, String value) {
        RedisCallback<Boolean> callback = (connection) -> connection.setNX(key.getBytes(), value.getBytes());
        return (Boolean) redisTemplate.execute(callback);
    }


    public static Long incrBy(String realKey, int step) {
        RedisCallback<Long> callback = (connection) -> connection.incrBy(realKey.getBytes(), step);
        return (Long) redisTemplate.execute(callback);
    }


}
